import 'package:flutter/material.dart';
import 'dart:async';

/// Stream 用法演示
class StreamDemo extends StatelessWidget {

  /// 覆盖 [build()] 方法
  /// 
  /// a param [context] type of [BuildContext]
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("StreamDemo"),
      ),
      body: StreamDemoHome(),
    );
  }
}

class StreamDemoHome extends StatefulWidget {
  @override
  _StreamDemoHomeState createState() => _StreamDemoHomeState();
}

class _StreamDemoHomeState extends State<StreamDemoHome> {

  StreamSubscription<String> _streamDemoSubscription;
  StreamController<String> _streamDemo;
  StreamSink _streamSink;

  /// 释放资源
  @override
  void dispose() {
    _streamDemo.close();
    super.dispose();
  }
 
  /// 初始化数据
  @override
  void initState() {
    super.initState();
    print("create stream...");
    // Stream<String> _streamDemo = Stream.fromFuture(fetchData());
    _streamDemo = StreamController<String>();
    _streamSink = _streamDemo.sink;
    print("start listen stream...");
    _streamDemoSubscription = _streamDemo.stream.listen((data) => print('$data'),
      onError: (error) { // 处理错误事件
        print('$error');
      },
      onDone: () {
        print('Done!');
      },
    );

    // _streamDemo.stream.listen((data) => print('onData2 ： $data'),
    //   onError: (error) { // 处理错误事件
    //     print('$error');
    //   },
    //   onDone: () {
    //     print('Done!');
    //   },
    // );

    // _streamDemoSubscription = _streamDemo.listen(
    //   (data) => print('$data'),
    //   onError: (error) { // 处理错误事件
    //     print('$error');
    //   },
    //   onDone: () {
    //     print('Done!');
    //   }
    // );

    print("initialize completed...");
  }

  Future<String> fetchData() async {
    // 让程序暂停3秒钟
    await Future.delayed(Duration(seconds: 3));
    return 'Hello ~~~';
  }

  /// 暂停Stream
  _pauseStream() {
    print("Pause Subscription");
    _streamDemoSubscription.pause();
  }

  /// 恢复Stream
  _resumeStream() {
    print("Resume Subscription");
    _streamDemoSubscription.resume();
  }

  /// 取消Stream
  _cancelStream() {
    print("Cancel Subscription");
    _streamDemoSubscription.cancel();
  }

  /// 往 stream 中添加数据
  _addDataToStream() async {
    print("add date to stream...");
    String data = await fetchData();
    // _streamDemo.add(data);
    if (data.isNotEmpty) {
      _streamSink.add(data);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("..."),
            // StreamBuilder(
            //   stream: _streamDemo.stream,
            //   initialData: "...",
            //   builder: (context, snapshop) {
            //     return Text('$snapshop.data');
            //   },
            // ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget> [
                FlatButton(
                  onPressed: _addDataToStream, 
                  child: Text("Add"),
                ),
                FlatButton(
                  onPressed: _pauseStream, 
                  child: Text("Pause"),
                ),
                FlatButton(
                  onPressed: _resumeStream, 
                  child: Text("Resume"),
                ),
                FlatButton(
                  onPressed: _cancelStream, 
                  child: Text("Cancel"),
                ),
              ],
            ),
          ]
        ),
      ),
    );
  }
}